<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin', 'admin', 0);
pc_base::load_sys_class('format', '', 0);
pc_base::load_sys_class('form', '', 0);

class manage extends admin
{

    private $db;

    public $siteid;

    public $agency_branch;

    public $agency_type;

    function __construct()
    {
        parent::__construct();
        pc_base::load_app_func('global');
        $this->db = pc_base::load_model('agency_nsr_model'); // 加载机构model
        $this->siteid = get_siteid(); // 获取当前站点ID
        $model_setting=pc_base::load_model('site_setting_model');//加载设置类model
        $this->agency_branch = $model_setting->getValue("agency_branch",$this->siteid);//获取机构校区
        $this->agency_type = $model_setting->getValue("agency_type",$this->siteid);//获取机构类型
        $this->admin_username = param::get_cookie('admin_username'); // 获取当前登录的管理员
    }

    /**
     * 机构列表
     * 
     */
    public function init()
    {
        $show_dialog = $show_validator = true;
        $show_header = '';
        $column = 'agency';
        $where .= " status = 1 and siteid =" . $this->siteid;
        //搜索框
        $name = empty($_GET['name']) ?'':$_GET['name'] ;#机构名称
        $branch = empty($_GET['branch']) ?'':$_GET['branch'];#机构校区
        $type = empty($_GET['type']) ?'':$_GET['type'];#机构类型
        if(!empty($name)){
            $where .= ' and name like "%'.$name.'%"';
        }
        if(!empty($branch)){
            $where .= ' and branch= '.$branch;
        }
        if(!empty($type)){
            $where .= ' and type= '.$type;
        }

        $agency_branch = $this->agency_branch;
        $agency_type = $this->agency_type;

        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;#获取页码
        //查询机构信息
        $agencyinfo = $this->db->select($where,"*","", 'update_time DESC , id DESC');#根据 update_time 降序排列
        $agencyinfo=getTreeList($agencyinfo,0);
        //获取管理员信息
        $admin_model = pc_base::load_model('admin_model'); // 加载admin_model
        $administrators = $admin_model->getRealnameInfo();
        //数据重构：加上最后编辑者信息
        foreach ($agencyinfo as $key=>$value){
            foreach ($administrators as $key2=>$value2){
                if($value['updated_by'] == $key2){
                    $value['publisher'] = $value2;
                    $agencyinfo[$key] = $value;
                    break;
                }
            }
        }
       // $pages = $this->db->pages;
        include $this->admin_tpl('agency_list');
    }

    /**
     * 机构添加
     */
    public function add()
    {
        //提交表单
        if (isset($_POST['dosubmit'])) {
            $data = isset($_POST['data']) ? $_POST['data'] : showmessage(L('illegal_parameters'), HTTP_REFERER);
            $data['created_by'] =  $_SESSION['userid'];#管理用户ID
            $data['updated_by'] =  $_SESSION['userid'];#管理用户ID
            $data['create_time'] = date("Y-m-d H:i:s",time());
            $data['update_time'] = date("Y-m-d H:i:s",time());
            $data['siteid'] = $this->siteid;
            $data['status'] = 1;#状态（0：禁用  1：可用  2：删除）
            $result = $this->db->insert($data,true);
            if ($result) {
            	//记录行为日志
            	$log_content = '<span style="color:green;">添加机构</span>[机构id：'.$result.'，机构名称：'.$data['full_name'].']';
            	$this->manage_admin_log($log_content);
                $url='?m=agency&c=manage&a=init';
                showmessage(L('add_success'), $url);
            } else {
                showmessage(L('add_error'), HTTP_REFERER);
            }
        } else {
            $column = 'agency';
            $agency_type = $this->agency_type;
            $agency_branch = $this->agency_branch;
            $show_dialog = $show_validator = true;
            $show_header = '';
            $id = isset($_GET['id']) ? $_GET['id'] :0;

            //$show_dialog = $show_validator = true;
            pc_base::load_sys_class('format', '', 0);
            pc_base::load_sys_class('form', '', 0);
            include $this->admin_tpl('agency_add');
        }
    }

    /**
     *机构编辑
     */
    public function edit()
    {
        //如果没获取到id，则视为非法请求
        $id = isset($_GET['id']) ? $_GET['id'] : showmessage(L('illegal_parameters'), HTTP_REFERER);
        $upinfo = $_POST['data'];
        //提交表单
        if (isset($_POST['dosubmit'])) {
            $data = isset($_POST['data']) ? $_POST['data'] : showmessage(L('illegal_parameters'), HTTP_REFERER);
            $data['updated_by'] =  $_SESSION['userid'];
            $data['update_time'] = date("Y-m-d H:i:s",time());
            $data['siteid'] = $this->siteid;
            $data['status'] = 1;#状态（0：禁用  1：可用  2：删除）
            $result = $this->db->update($data, array(
                'id' => $id
            ));
            if ($result) {
            	//记录行为日志
            	$log_content = '<span style="color:blue;">修改机构</span>[机构id：'.$id.'，机构名称：'.$data['full_name'].']';
            	$this->manage_admin_log($log_content);
                $url='?m=agency&c=manage&a=init';
                showmessage(L('edit_success'), $url);
            } else {
                showmessage(L('edit_error'), HTTP_REFERER);
            }
        } else {
            $data = $this->db->get_one(array(
                'id' => $id
            ));
            $column="agency";
            $show_dialog = $show_validator = true;
            $agency_branch = $this->agency_branch;
            $agency_type = $this->agency_type;
            $show_header = '';
            include $this->admin_tpl('agency_edit');
        }
    }

    /**
     * 删除、批量删除机构
     */
    public function del()
    {
        //如果没获取到id，则视为非法请求
        if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = $_REQUEST['id'];
        $agency_id = $id;
        $remindInfo = '该机构有正在进行的课程，请先删除相应的课程！';
        $course_nsr_model = pc_base::load_model('course_nsr_model'); // 加载course_nsr_model
        //查询机构下是否有正在进行的课程
        $temp = $course_nsr_model->check_course($agency_id);
        if (is_array($id)) {
            foreach ($id as $k => $v) {
                //如果有正在进行的课程就不允许删除机构的操作
                if($course_nsr_model->check_course($v)){
                    showmessage($remindInfo, HTTP_REFERER);
                    return false;
                }

                if (intval($v)) {
                    $id[$k] = intval($v);
                } else {
                    unset($id[$k]);
                }
            }
            $id = implode('\',\'', $id);
        }else{
            //当$id为非数组时
            if($course_nsr_model->check_course($id)){
                showmessage($remindInfo, HTTP_REFERER);
                return false;
            }
        }
        $result = $this->db->update(array(
            'status' => '2'#状态（0：禁用  1：可用  2：删除）
        ), "id in ('$id')");
        $result2 = $course_nsr_model->update(array(
            'status' => '2'#状态（0：禁用  1：可用  2：删除）
        ), array('agency_id'=>$agency_id));
        
        
        if ($result && $result2) {
        	//记录行为日志
        	$del_id = explode('\',\'', $id);
        	$new_id = implode('，', $del_id);
        	$log_content = '<span style="color:red;">删除机构</span>[机构id：'.$new_id.']';
        	$this->manage_admin_log($log_content);
            showmessage(L('del_success'), HTTP_REFERER);
        } else {
            showmessage(L('del_error'), HTTP_REFERER);
        }
    }

    /*
     * 机构详情
     */
    public function view()
    {
        //如果没获取到id，则视为非法请求
        if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $column = agency;
        $id = $_REQUEST['id'];
        $data = $this->db->get_one(array(
            'id' => $id
        ));
        $show_header = '';
        include $this->admin_tpl('agency_view');
    }
}